package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

//Java：组合总和 III
public class CombinationSumIii {
    public static void main(String[] args) {
        Solution solution = new CombinationSumIii().new Solution();
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {

        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();

        public List<List<Integer>> combinationSum3(int k, int n) {
            backtracking(n, k, 1, 0);
            return result;
        }

        private void backtracking(int targetSum, int k, int startIndex, int sum) {
            if (sum > targetSum) {
                return;
            }
            if (path.size() == k && sum == targetSum) {
                result.add(new ArrayList<>(path));
                return;
            }
            // 减枝 9 - (k - path.size()) + 1。也可以为i<=9
            for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
                path.add(i);
                sum += i;
                backtracking(targetSum, k, i + 1, sum);
                //回溯
                path.removeLast();
                //回溯
                sum -= i;
            }
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}